<template>
  <div class="categories">
    <el-breadcrumb separator="/" style="margin-bottom: 20px;">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="line-height: 0; text-align: left;">
      <el-row style="margin-bottom: 30px;">
        <el-button type="primary" @click="addCategoryDialogVisible = true">添加分类</el-button>
      </el-row>
      <el-table :data="categoryList" style="width: 100%;margin-bottom: 20px;" border
        :tree-props="{ children: 'children' }" row-key="cat_id">
        <el-table-column prop="cat_id" label="#" sortable width="180">

        </el-table-column>
        <el-table-column prop="cat_name" label="分类名称" sortable width="180">
        </el-table-column>
        <el-table-column prop="cat_id" label="是否有效">
        </el-table-column>
        <el-table-column prop="address" label="排序">
          <template slot-scope="scope">
            <!-- 一级二级三级分类按钮 -->
            <el-button :type="scope.row.cat_level == 0 ? 'primary' : scope.row.cat_level == 1 ? 'success' : 'warning'">
              {{ scope.row.cat_level == 0 ? '一级' : scope.row.cat_level == 1 ? '二级' : '三级' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <!-- 编辑点击事件 -->
            <el-button type="primary" size="mini" @click="handleEditCategory(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDeleteCategory(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="添加分类" :visible.sync="addCategoryDialogVisible" width="30%" center style="line-height: 0;">
      <el-form :model="addCategoryForm" ref="addCategoryForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addCategoryForm.name"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="addCategoryForm" ref="addCategoryForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="父级分类" prop="name">
          <div class="block">
            <el-cascader v-model="addCategoryForm.cateValue" :options="categoryList" :props="{
              checkStrictly: true,
              label: 'cat_name',
              value: 'cat_id',
              children: 'children'
            }" clearable @change="handleParentCategoryChange"></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddCategory">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑分类" :visible.sync="editCategoryDialogVisible" width="30%" center style="line-height: 0;">
      <el-form ref="editCategoryForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="editCategoryForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import http from '@/mixins/http';
// 封装数据请求方法
const categoryApi = {
  getCategories: async function (context, params) {
    try {
      return await context.$httpGet('/categories', params);
    } catch (error) {
      console.error('获取分类列表失败:', error);
      context.$message.error('获取分类列表失败');
      return null;
    }
  },
  addCategory: async function (context, data) {
    try {
      return await context.$httpPost('/categories', data);
    } catch (error) {
      console.error('添加分类失败:', error);
      context.$message.error('添加分类失败');
      return null;
    }
  },
  updateCategory: async function (context, categoryId, data) {
    try {
      return await context.$httpPut(`/categories/${categoryId}`, data);
    } catch (error) {
      console.error('编辑分类失败:', error);
      context.$message.error('编辑分类失败');
      return null;
    }
  },
  deleteCategory: async function (context, categoryId) {
    try {
      return await context.$httpDelete(`/categories/${categoryId}`);
    } catch (error) {
      console.error('删除分类失败:', error);
      context.$message.error('删除分类失败');
      return null;
    }
  }
};

export default {
  mixins: [http()],
  data() {
    return {
      categoryList: [],
      baseURL: 'http://43.138.15.137:7000/api/private/v1',
      token: localStorage.getItem('token'),
      addCategoryDialogVisible: false,
      pagination: {
        pageSize: 10,
        pageNum: 1,
        type: 3,
      },
      addCategoryForm: {
        name: '',
        cateValue: [],
        categoryId: 0,
        cat_level: 0,
      },
      editCategoryDialogVisible: false,
      editCategoryForm: {
        cat_id: 0,
        cat_name: '',
        cat_level: 0,
      }
    }
  },
  created() {
    this.fetchCategoryList();
  },
  methods: {
    async fetchCategoryList() {
      const params = {
        type: this.pagination.type,
        pagenum: this.pagination.pageNum,
        pagesize: this.pagination.pageSize
      };
      const res = await categoryApi.getCategories(this, params);
      if (res) {
        this.categoryList = res.data.data.result;
      }
    },
    handleParentCategoryChange() {
      this.addCategoryForm.categoryId = this.addCategoryForm.cateValue[this.addCategoryForm.cateValue.length - 1];
      console.log('父级分类ID:', this.addCategoryForm.categoryId);
      this.addCategoryForm.cat_level = this.addCategoryForm.cateValue.length;
      console.log('分类级别:', this.addCategoryForm.cat_level);
    },
    async handleAddCategory() {
      if (!this.addCategoryForm.name.trim()) {
        this.$message({
          message: '请输入分类名称',
          type: 'warning'
        });
        return;
      }
      const data = {
        cat_pid: this.addCategoryForm.categoryId,
        cat_name: this.addCategoryForm.name,
        cat_level: this.addCategoryForm.cat_level
      };
      const res = await categoryApi.addCategory(this, data);
      if (res) {
        this.$message({
          message: '添加成功',
          type: 'success'
        });
        this.fetchCategoryList();
        this.addCategoryDialogVisible = false;
        this.resetAddCategoryForm();
      }
    },
    resetAddCategoryForm() {
      this.addCategoryForm.name = '';
      this.addCategoryForm.cateValue = [];
      this.addCategoryForm.categoryId = 0;
      this.addCategoryForm.cat_level = 0;
    },
    handleEditCategory(row) {
      this.editCategoryDialogVisible = true;
      this.editCategoryForm.cat_id = row.cat_id;
      this.editCategoryForm.cat_name = row.cat_name;
      console.log('编辑分类数据:', this.editCategoryForm);
    },
    async handleEditSubmit() {
      const data = {
        cat_name: this.editCategoryForm.cat_name
      };
      const res = await categoryApi.updateCategory(this, this.editCategoryForm.cat_id, data);
      if (res) {
        this.$message({
          message: '编辑成功',
          type: 'success'
        });
        this.fetchCategoryList();
        this.editCategoryDialogVisible = false;
      }
    },
    async handleDeleteCategory(row) {
      this.editCategoryForm.cat_id = row.cat_id;
      this.$confirm('确定删除该分类吗？是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await categoryApi.deleteCategory(this, this.editCategoryForm.cat_id);
        if (res) {
          const { meta } = res.data;
          if (meta.status === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }
          this.fetchCategoryList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>
